package cn.zmit.kuxi.activity;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.TabActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.Toast;
import cn.zmit.kuxi.R;
import cn.zmit.kuxi.contants.SPConstants;
import cn.zmit.kuxi.event.Event;
import cn.zmit.kuxi.event.EventType;
import cn.zmit.kuxi.request.RequestTask;
import cn.zmit.kuxi.service.JPushService;

import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.xdroid.common.utils.PreferenceHelper;
import com.xdroid.eventbus.EventBus;
import com.xdroid.functions.request.JsonData;
import com.xdroid.request.extension.XDroidRequest;
import com.xdroid.request.extension.config.DataType;
import com.xdroid.request.extension.impl.OnRequestListenerAdapter;
import com.xdroid.utils.AppManager;
import com.xdroid.view.XDroidBadgeView;

/** * @author @parameter * @return */
public class HomeActivity extends TabActivity {

	private TabHost mTabHost;
	@ViewInject(R.id.home_radio_button_group)
	private RadioGroup mTabButtonGroup;
	@ViewInject(R.id.home_tab_main)
	private RadioButton home_tab_main;
	@ViewInject(R.id.home_tab_goods)
	private RadioButton home_tab_goods;
	@ViewInject(R.id.home_tab_winner)
	private RadioButton home_tab_winner;
	@ViewInject(R.id.home_tab_shoppingcarts)
	private RadioButton home_tab_shoppingcarts;
	@ViewInject(R.id.home_tab_user)
	private RadioButton home_tab_user;
	private RadioButton home_tab_collect;
	private static final String TAB_MAIN = "MAIN_ACTIVITY";// ��ҳ
	private static final String TAB_GOODS = "GOODS_ACTIVITY";//
	private static final String TAB_WINNER = "WINNER_ACTIVITY";
	private static final String TAB_SHOPPING = "SHOPPING_ACTIVITY";
	private static final String TAB_USER = "USER_ACTIVITY";

	@ViewInject(R.id.rl_brage)
	private RelativeLayout rl_brage;

	private XDroidBadgeView badgeView;
	private String userid;
	Boolean haslog;
	private int count = 0;

	public static int amount = 0;
	Intent intentService;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		AppManager.getInstance().addActivity(this);
		setContentView(R.layout.activity_home);
		ViewUtils.inject(this);
		EventBus.getDefault().register(this);// 注册

		intentService = new Intent(this, JPushService.class);
		// // jpush
		// startService(intentService);
		// stopJpushService
		if (isServiceWork(this, "cn.zmit.kuxi.service.JPushService")) {
			stopService(intentService);
		}

		initView();

		// 首先要判断用户是否登录
		haslog = PreferenceHelper.readBoolean(this,
				SPConstants.SHARED_PREFERENCE_NAME, SPConstants.HAS_LOGGED,
				false);
		if (haslog) {
			userid = PreferenceHelper.readString(this,
					SPConstants.SHARED_PREFERENCE_NAME, SPConstants.USERID, "");
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("user_id", userid);
			RequestTask.getInstance().doShoppingCarts(this, map,
					new onRequestListener());
		}

		// jumpHomeActivity
		Intent intent = getIntent();
		int jump_index = intent.getIntExtra("jump_index", 0);
		jumpActivity(jump_index);
	}

	public void jumpActivity(int index) {
		switch (index) {
		case 0:
			mTabHost.setCurrentTabByTag(TAB_MAIN);
			home_tab_main.setChecked(true);
			break;
		case 1:
			mTabHost.setCurrentTabByTag(TAB_GOODS);
			home_tab_goods.setChecked(true);
			break;
		case 2:
			mTabHost.setCurrentTabByTag(TAB_WINNER);
			home_tab_winner.setChecked(true);
			break;
		case 3:
			mTabHost.setCurrentTabByTag(TAB_SHOPPING);
			home_tab_shoppingcarts.setChecked(true);
			break;
		case 4:
			mTabHost.setCurrentTabByTag(TAB_USER);
			home_tab_user.setChecked(true);
			break;

		default:
			break;
		}
	}

	private class onRequestListener extends OnRequestListenerAdapter<Object> {
		public void onDone(XDroidRequest<?> request, String response,
				DataType dataType) {
			super.onDone(request, response, dataType);
			JsonData jsonData = JsonData.create(response);
			JsonData data = jsonData.optJson("shopping_cart");

			if (data != null && data.length() > 0) {
				count = data.length();
				initbage();
			} else {
				count = 0;
				initbage();
			}
		}
	}

	public void initbage() {// 初始化购物车角标
		Log.e("count1", count + "");
		badgeView = new XDroidBadgeView(this, rl_brage);
		badgeView.setTextSize(10);
		badgeView.setText(count + "");
		badgeView.setBadgePosition(XDroidBadgeView.POSITION_TOP_RIGHT);
		badgeView.show();
	}

	private void initView() {// 初始化底部栏

		mTabHost = getTabHost();

		Intent i_main = new Intent(this, MainActivity.class);
		Intent i_goods = new Intent(this, GoodsActivity.class);
		Intent i_newWinner = new Intent(this, NewWinnerActivity.class);
		Intent i_shoppingCarts = new Intent(this, ShoppingCartsActivity.class);

		Intent i_user = new Intent(this, UserActivity.class);

		mTabHost.addTab(mTabHost.newTabSpec(TAB_MAIN).setIndicator(TAB_MAIN)
				.setContent(i_main));
		mTabHost.addTab(mTabHost.newTabSpec(TAB_GOODS).setIndicator(TAB_GOODS)
				.setContent(i_goods));
		mTabHost.addTab(mTabHost.newTabSpec(TAB_WINNER)
				.setIndicator(TAB_WINNER).setContent(i_newWinner));
		mTabHost.addTab(mTabHost.newTabSpec(TAB_SHOPPING)
				.setIndicator(TAB_SHOPPING).setContent(i_shoppingCarts));
		mTabHost.addTab(mTabHost.newTabSpec(TAB_USER).setIndicator(TAB_USER)
				.setContent(i_user));

		mTabHost.setCurrentTabByTag(TAB_MAIN);

		mTabButtonGroup
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {
					@Override
					public void onCheckedChanged(RadioGroup group, int checkedId) {
						switch (checkedId) {
						case R.id.home_tab_main:
							mTabHost.setCurrentTabByTag(TAB_MAIN);
							break;
						case R.id.home_tab_goods:
							mTabHost.setCurrentTabByTag(TAB_GOODS);
							break;
						case R.id.home_tab_winner:
							mTabHost.setCurrentTabByTag(TAB_WINNER);
							break;
						case R.id.home_tab_shoppingcarts:
							mTabHost.setCurrentTabByTag(TAB_SHOPPING);
							break;
						case R.id.home_tab_user:
							mTabHost.setCurrentTabByTag(TAB_USER);
							break;
						default:
							break;
						}
					}
				});
	}

	/**
	 * 接收event事件
	 * 
	 * @param event
	 */
	public void onEventMainThread(Event<Integer> event) {
		if (event.getEventType() == EventType.HOME_INDEX) {
			switch (event.getExtraData()) {
			case 0:
				mTabHost.setCurrentTabByTag(TAB_MAIN);// 首页
				home_tab_main.setChecked(true);
				break;
			case 1:
				mTabHost.setCurrentTabByTag(TAB_GOODS);// 商品
				home_tab_goods.setChecked(true);
				break;
			case 2:
				mTabHost.setCurrentTabByTag(TAB_WINNER);// 最新战报
				home_tab_winner.setChecked(true);
				break;
			case 3:
				mTabHost.setCurrentTabByTag(TAB_SHOPPING);// 购物车
				home_tab_shoppingcarts.setChecked(true);
				break;
			case 4:
				mTabHost.setCurrentTabByTag(TAB_USER);// 用户中心
				home_tab_user.setChecked(true);
				break;
			}
		} else if (event.getEventType() == EventType.CART_COUT) {
			badgeView.setText(event.getExtraData() + "");
			badgeView.show();
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		// jpush
		startService(intentService);
		EventBus.getDefault().unregister(this);// 取消注册

	}

	/**
	 * 退出程序
	 */
	private long exitTime = 0;

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
			if (event.getAction() == KeyEvent.ACTION_DOWN
					&& event.getRepeatCount() == 0) {
				this.exitApp();
			}
			return true;
		}
		return super.dispatchKeyEvent(event);
	}

	private void exitApp() {
		// 判断2次点击事件时间
		if ((System.currentTimeMillis() - exitTime) > 2000) {

			Toast.makeText(HomeActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT)
					.show();
			exitTime = System.currentTimeMillis();
		} else {
			// android.os.Process.killProcess(android.os.Process.myPid());
			// finish();
			// 结束所有activity
			AppManager.getInstance().killAllActivity();
		}
	}

	/**
	 * 判断某个服务是否正在运行的方法
	 * 
	 * @param mContext
	 * @param serviceName
	 *            是包名+服务的类名（例如：net.loonggg.testbackstage.TestService）
	 * @return true代表正在运行，false代表服务没有正在运行
	 */
	public boolean isServiceWork(Context mContext, String serviceName) {
		boolean isWork = false;
		ActivityManager myAM = (ActivityManager) mContext
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningServiceInfo> myList = myAM.getRunningServices(40);
		if (myList.size() <= 0) {
			return false;
		}
		for (int i = 0; i < myList.size(); i++) {
			String mName = myList.get(i).service.getClassName().toString();
			if (mName.equals(serviceName)) {
				isWork = true;
				break;
			}
		}
		return isWork;
	}
}
